package com.zby.common.exception;

import com.zby.common.utils.ResultUtil;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
@Hidden
public class GlobalExceptionHandler {
    /**
     * 通用异常处理方法（处理所有Throwable及其子类异常）
     * 遍历异常原因链，获取第一个包含本地化消息的异常信息
     *
     * @param e 捕获到的异常对象
     * @return ResultUtil<Object> 包含错误码和错误消息的响应对象
     *         默认错误码为失败状态，消息取自第一个有本地化消息的异常
     */
    @ExceptionHandler(Throwable.class)
    public ResultUtil<Object> getException(Throwable e) {
        ResultUtil<Object> result = ResultUtil.fail();
        while (!ObjectUtils.isEmpty(e)) {
            if (!ObjectUtils.isEmpty(e.getLocalizedMessage())) {
                log.error(e.getLocalizedMessage());
                result.setMsg(e.getLocalizedMessage());
                break;
            }
            e = e.getCause();
        }
        return result;
    }

    /**
     * 处理自定义BlogException异常
     *
     * @param e 捕获到的BlogException异常实例
     * @return ResultUtil<Object> 包含特定错误码和消息的响应对象
     *         错误码和消息直接取自异常对象本身
     */
    @ExceptionHandler(BlogException.class)
    public ResultUtil<Object> getBlogException(BlogException e) {
        ResultUtil<Object> result = new ResultUtil<>();
        result.setCode(e.getCode());
        result.setMsg(e.getLocalizedMessage());
        return result;
    }
    @ExceptionHandler(RateLimitException.class)
    public ResultUtil<Object> handleRateLimit(BlogException e) {
        ResultUtil<Object> result = new ResultUtil<>();
        result.setCode(e.getCode());
        result.setMsg(e.getLocalizedMessage());
        return result;
    }
}
